<template>
  <div class="task-management">
    <TopNavigation :showOrganizationSection="false" :showTaskRoleSection="false" />
    
    <div class="container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>任务管理</h2>
      </div>
      
      <!-- 搜索和操作区域 -->
      <div class="search-action-container">
        <div class="search-input-wrapper">
          <input 
            type="text" 
            class="input search-input" 
            v-model="searchKeyword" 
            placeholder="搜索？搜就完了！"
            @keyup.enter="handleSearch"
          >
          <button class="search-btn" @click="handleSearch">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <circle cx="11" cy="11" r="8"></circle>
              <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
            </svg>
          </button>
        </div>
        
        <button class="btn btn-primary new-task-btn" @click="showNewTaskModal = true">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <line x1="12" y1="5" x2="12" y2="19"></line>
            <line x1="5" y1="12" x2="19" y2="12"></line>
          </svg>
          新建任务
        </button>
      </div>
      
      <!-- 任务列表区域 -->
      <div class="task-list-section">
        <div v-if="tasks.length > 0" class="task-table">
          <table class="data-table">
            <thead>
              <tr>
                <th>任务名称</th>
                <th>数据源配置</th>
                <th>流程定义</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="task in tasks" :key="task.id">
                <td>{{ task.title }}</td>
                <td>{{ task.dataSource ? getDataSourceName(task.dataSource) : '未设置' }}</td>
                <td>{{ task.processDefinition ? getProcessName(task.processDefinition) : '未设置' }}</td>
                <td>
                  <div class="task-actions">
                    <button class="btn btn-secondary btn-sm" @click="viewTaskDetail(task)">
                      查看
                    </button>
                    <button class="btn btn-primary btn-sm" @click="editTask(task)">
                      编辑
                    </button>
                    <button class="btn btn-danger btn-sm" @click="deleteTask(task.id)">
                      删除
                    </button>
                    <button class="btn btn-warning btn-sm" @click="toggleTaskStatus(task)">
                      {{ task.status === 'processing' || task.status === 'pending' ? '停用' : '启用' }}
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        
        <!-- 无任务状态 -->
        <div v-else class="no-tasks">
          <div class="no-tasks-icon">
            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">
              <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
              <line x1="16" y1="2" x2="16" y2="6"></line>
              <line x1="8" y1="2" x2="8" y2="6"></line>
              <line x1="3" y1="10" x2="21" y2="10"></line>
            </svg>
          </div>
          <p class="no-tasks-text">暂无任务</p>
          <p class="no-tasks-subtext">开始创建您的第一个任务</p>
        </div>
      </div>
    </div>
    
    <!-- 新建任务模态框 -->
    <NewTaskModal 
      v-if="showNewTaskModal" 
      @close="showNewTaskModal = false"
      @created="handleTaskCreated"
    />
    
    <!-- 任务详情模态框 -->
    <TaskDetailModal 
      :visible="showTaskDetailModal" 
      :task="selectedTask" 
      :is-edit-mode="isEditMode"
      @close="handleTaskDetailClose"
      @task-updated="handleTaskUpdated"
    />
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { getTaskList } from '../services/taskService';
import TopNavigation from '../components/TopNavigation.vue';
import NewTaskModal from '../components/NewTaskModal.vue';
import TaskDetailModal from '../components/TaskDetailModal.vue';
import router from '../router';

export default {
  name: 'TaskManagement',
  components: {
    TopNavigation,
    NewTaskModal,
    TaskDetailModal
  },
  setup() {
    // 任务列表
    const tasks = ref([]);
    // 搜索关键词
    const searchKeyword = ref('');
    // 是否显示新建任务模态框
    const showNewTaskModal = ref(false);
    // 是否显示任务详情模态框
    const showTaskDetailModal = ref(false);
    // 选中的任务
    const selectedTask = ref(null);
    // 是否处于编辑模式
    const isEditMode = ref(false);
    
    // 获取任务列表
    const fetchTasks = async () => {
      try {
        const response = await getTaskList({
          page: 1,
          pageSize: 20,
          // 可以根据需要添加其他过滤条件
        });
        
        // 如果API返回了数据，就使用真实数据
        if (response && response.data && response.data.length > 0) {
          tasks.value = response.data;
        } else {
          // 如果没有数据，使用模拟数据
          tasks.value = [
            {
              id: '1',
              title: '数据同步任务',
              taskType: '数据处理',
              department: '技术部',
              status: 'processing',
              createdAt: '2023-05-15T09:30:00Z',
              dataSource: 'ds1',
              processDefinition: 'proc1'
            },
            {
              id: '2',
              title: '系统升级部署',
              taskType: '系统维护',
              department: '运维部',
              status: 'pending',
              createdAt: '2023-05-14T14:20:00Z',
              dataSource: 'ds2',
              processDefinition: 'proc2'
            },
            {
              id: '3',
              title: '性能优化测试',
              taskType: '测试验证',
              department: '测试部',
              status: 'completed',
              createdAt: '2023-05-10T11:15:00Z',
              dataSource: 'ds3',
              processDefinition: 'proc3'
            }
          ];
        }
      } catch (error) {
        console.error('获取任务列表失败:', error);
        // 发生错误时也使用模拟数据
        tasks.value = [
          {
            id: '1',
            title: '数据同步任务',
            taskType: '数据处理',
            department: '技术部',
            status: 'processing',
            createdAt: '2023-05-15T09:30:00Z',
            dataSource: 'ds1',
            processDefinition: 'proc1'
          },
          {
            id: '2',
            title: '系统升级部署',
            taskType: '系统维护',
            department: '运维部',
            status: 'pending',
            createdAt: '2023-05-14T14:20:00Z',
            dataSource: 'ds2',
            processDefinition: 'proc2'
          },
          {
            id: '3',
            title: '性能优化测试',
            taskType: '测试验证',
            department: '测试部',
            status: 'completed',
            createdAt: '2023-05-10T11:15:00Z',
            dataSource: 'ds3',
            processDefinition: 'proc3'
          }
        ];
      }
    };
    
    // 处理搜索
    const handleSearch = async () => {
      try {
        const response = await getTaskList({
          page: 1,
          pageSize: 20,
          keyword: searchKeyword.value
        });
        tasks.value = response.data || [];
      } catch (error) {
        console.error('搜索任务失败:', error);
      }
    };
    
    // 查看任务详情
    const viewTaskDetail = (task) => {
      console.log('查看任务详情:', task.id);
      selectedTask.value = task;
      showTaskDetailModal.value = true;
    };
    
    // 处理任务创建成功
    const handleTaskCreated = (newTask) => {
      // 如果有新任务数据直接添加到列表中（适用于模拟环境）
      if (newTask && typeof newTask === 'object') {
        // 添加新任务到列表顶部
        tasks.value.unshift(newTask);
        
        // 在离线模式下，不再调用fetchTasks以避免覆盖新添加的任务
        console.log('新任务已添加到列表中');
        return;
      } else if (!newTask) {
        // 如果没有新任务数据，但API可能返回了结果，我们创建一个模拟的新任务添加到列表中
        const mockNewTask = {
          id: Date.now().toString(), // 生成一个唯一ID
          title: '新建任务',
          taskType: '自定义任务',
          department: '默认部门',
          status: 'pending',
          createdAt: new Date().toISOString(),
          dataSource: 'ds1',
          processDefinition: 'proc1'
        };
        tasks.value.unshift(mockNewTask);
        
        // 在离线模式下，不再调用fetchTasks以避免覆盖新添加的任务
        console.log('模拟任务已添加到列表中');
        return;
      }
      
      // 在实际API成功的情况下，仍然调用fetchTasks确保数据同步
      // fetchTasks();
    };
    
    // 处理任务更新
    const handleTaskUpdated = (updatedTask) => {
      console.log('任务已更新:', updatedTask);
      // 在任务列表中找到并更新对应的任务
      const taskIndex = tasks.value.findIndex(task => task.id === updatedTask.id);
      if (taskIndex !== -1) {
        tasks.value[taskIndex] = updatedTask;
      }
      // 重置编辑模式状态
      isEditMode.value = false;
    };
    
    // 关闭任务详情模态框时重置编辑模式
    const handleTaskDetailClose = () => {
      showTaskDetailModal.value = false;
      isEditMode.value = false;
    };
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'pending': '待处理',
        'processing': '处理中',
        'completed': '已完成',
        'cancelled': '已取消'
      };
      return statusMap[status] || status;
    };
    
    // 获取数据源配置名称
    const getDataSourceName = (dataSourceId) => {
      const dataSourceMap = {
        'ds1': 'MySQL 数据源',
        'ds2': 'PostgreSQL 数据源',
        'ds3': 'MongoDB 数据源'
      };
      return dataSourceMap[dataSourceId] || dataSourceId;
    };
    
    // 获取流程定义名称
    const getProcessName = (processId) => {
      const processMap = {
        'proc1': '标准审批流程',
        'proc2': '快速部署流程',
        'proc3': '测试验证流程'
      };
      return processMap[processId] || processId;
    };
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN');
    };
    
    // 编辑任务
    const editTask = (task) => {
      console.log('编辑任务:', task);
      selectedTask.value = task;
      isEditMode.value = true;
      showTaskDetailModal.value = true;
    };
    
    // 删除任务
    const deleteTask = (taskId) => {
      if (confirm('确定要删除这个任务吗？')) {
        // 实际项目中可以调用删除API
        tasks.value = tasks.value.filter(task => task.id !== taskId);
        console.log('删除任务:', taskId);
      }
    };
    
    // 切换任务状态（启用/停用）
    const toggleTaskStatus = (task) => {
      // 实际项目中可以调用更新状态API
      const newStatus = task.status === 'processing' || task.status === 'pending' ? 'cancelled' : 'pending';
      const taskIndex = tasks.value.findIndex(t => t.id === task.id);
      if (taskIndex !== -1) {
        tasks.value[taskIndex].status = newStatus;
      }
      console.log('切换任务状态:', task.id, newStatus);
    };
    
    // 初始加载
    onMounted(() => {
      fetchTasks();
    });
    
    return {
      tasks,
      searchKeyword,
      showNewTaskModal,
      showTaskDetailModal,
      selectedTask,
      isEditMode,
      handleSearch,
      viewTaskDetail,
      handleTaskCreated,
      handleTaskUpdated,
      handleTaskDetailClose,
      getStatusText,
      formatDate,
      getDataSourceName,
      getProcessName,
      editTask,
      deleteTask,
      toggleTaskStatus
    };
  }
};
</script>

<style scoped>
.task-management {
  background-color: var(--bg-light);
  min-height: 100vh;
  width: 100%;
}

.container {
  padding: 10px 20px 20px 20px; /* 减少顶部内边距 */
  max-width: 1400px; /* 增加最大宽度 */
  margin: 0 auto;
  width: 100%;
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid var(--border-base);
}

.page-header h2 {
  margin: 0;
  color: var(--text-primary);
  font-size: 24px;
  font-weight: 600;
}

.search-action-container {
      display: flex;
      align-items: center;
      gap: 15px;
      margin-bottom: 15px;
      flex-wrap: wrap;
    }

    .search-input-wrapper {
      position: relative;
      max-width: 400px;
      width: 100%;
      flex: 1;
    }

.search-input {
  padding-right: 45px;
  width: 100%;
}

.search-btn {
  position: absolute;
  right: 2px;
  top: 2px;
  bottom: 2px;
  width: 40px;
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: calc(var(--border-radius-base) - 2px);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.3s ease;
}

.search-btn:hover {
      background-color: var(--primary-hover);
    }

    .new-task-btn {
      white-space: nowrap;
    }

    /* 针对小屏幕的响应式调整 */
    @media (max-width: 768px) {
      .search-action-container {
        flex-direction: column;
        align-items: stretch;
      }
      
      .new-task-btn {
        width: 100%;
        justify-content: center;
      }
    }

.task-list-section {
  background-color: var(--bg-white);
  border-radius: var(--border-radius-md);
  padding: 20px;
  box-shadow: var(--shadow-base);
  width: 100%;
  box-sizing: border-box;
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

.data-table th {
  background-color: #f5f5f5;
  padding: 12px 15px;
  text-align: left;
  font-weight: 600;
  color: var(--text-primary);
  border-bottom: 2px solid #e8e8e8;
  font-size: 14px;
}

.data-table td {
  padding: 12px 15px;
  border-bottom: 1px solid #e8e8e8;
  color: var(--text-regular);
  font-size: 14px;
}

.data-table tr:hover {
  background-color: #fafafa;
}

.task-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.btn-sm {
  padding: 4px 12px;
  font-size: 12px;
  min-width: 60px;
}

.btn-warning {
  background-color: #faad14;
  border-color: #faad14;
  color: white;
}

.btn-warning:hover {
  background-color: #d48806;
  border-color: #d48806;
}

.btn-danger {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
  color: white;
}

.btn-danger:hover {
  background-color: #cf1322;
  border-color: #cf1322;
}

/* 针对小屏幕的响应式调整 */
@media (max-width: 768px) {
  .task-actions {
    flex-direction: column;
    align-items: stretch;
  }
  
  .btn-sm {
    width: 100%;
  }
}

.no-tasks {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
  color: var(--text-secondary);
  flex: 1;
}

.no-tasks-icon {
  margin-bottom: 15px;
  color: var(--text-placeholder);
}

.no-tasks-text {
  margin: 0 0 5px 0;
  font-size: 16px;
  font-weight: 500;
}

.no-tasks-subtext {
  margin: 0;
  font-size: 14px;
}
</style>